package com.gw.jpa.controller;

import com.gw.jpa.entity.User;
import com.gw.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController//每个方法都支持json格式
public class UserController {//控制器：接收前端的请求，把后端返回给前端
    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{uid}")
    //根据用户id查询用户信息，返回user对象
    public User getUser(@PathVariable("uid") Integer uid) {
        User user = null;
        //调用业务逻辑层根据uid查询用户
        user = userRepository.findById(uid).get();
        return user;
    }

    //添加用户
    @PostMapping("/user")
    public User addUser(User user) {
        //调用repository添加用户的方法
        User user1 = null;
        user1 = userRepository.save(user);
        return user1;
    }

    //修改用户
    @PutMapping("/user")
    public User modifyUser(User user) {
        User user1 = userRepository.save(user);
        return user1;
    }

    //根据用户id删除用户
    @DeleteMapping("/user/{uid}")
    public void deleteUserByUid(@PathVariable("uid") Integer uid) {
        userRepository.deleteById(uid);
    }

    //获取所有用户列表
    @GetMapping("/user")
    public List<User> getUsers() {
        List<User> userList = userRepository.findAll();
        return userList;
    }
}
